<template>
  <view class="py-base">
    <u-form
      :model="formData"
      :rules="formRules"
      errorType="border-bottom"
      ref="formRef"
    >
      <u-form-item>
        <view class="px-base pt-sm">
          <u--text type="info" text="基本信息"></u--text>
        </view>
      </u-form-item>
      <u-form-item
        prop="account"
        :border-bottom="true"
        :custom-style="{ backgroundColor: '#ffffff' }"
      >
        <view class="w-100 px-base bg-white u-flex-y-center">
          <view>用&ensp;户&ensp;名：</view>
          <u-input
            v-model="formData.account"
            placeholder='字母、数字或"_"，6~30位'
            border="none"
            input-align="right"
            class="u-flex-grow"
            @focus="$refs.formRef.clearValidate('account')"
          ></u-input>
        </view>
      </u-form-item>
      <u-form-item
        prop="password"
        :border-bottom="true"
        :custom-style="{ backgroundColor: '#ffffff' }"
      >
        <view class="w-100 px-base bg-white u-flex-y-center">
          <view>密&emsp;&emsp;码：</view>
          <u-input
            v-model="formData.password"
            placeholder='字母、数字或"_"组合，6~30位'
            type="password"
            border="none"
            input-align="right"
            @focus="$refs.formRef.clearValidate('password')"
          ></u-input>
        </view>
      </u-form-item>
      <u-form-item
        prop="passwordConfirm"
        :border-bottom="true"
        :custom-style="{ backgroundColor: '#ffffff' }"
      >
        <view class="w-100 px-base bg-white u-flex-y-center">
          <view>确认密码：</view>
          <u-input
            v-model="formData.passwordConfirm"
            placeholder="请再次输入密码"
            type="password"
            border="none"
            input-align="right"
            @focus="$refs.formRef.clearValidate('passwordConfirm')"
          ></u-input>
        </view>
      </u-form-item>

      <u-form-item>
        <view class="px-base pt-sm">
          <u--text type="info" text="证件信息"></u--text>
        </view>
      </u-form-item>
      <u-form-item
        prop="name"
        :border-bottom="true"
        :custom-style="{ backgroundColor: '#ffffff' }"
      >
        <view class="w-100 px-base bg-white u-flex-y-center">
          <view>姓&emsp;&emsp;名：</view>
          <u-input
            v-model="formData.name"
            placeholder="请输入真实姓名,以便购票"
            border="none"
            input-align="right"
            class="u-flex-grow"
            @focus="$refs.formRef.clearValidate('name')"
          ></u-input>
        </view>
      </u-form-item>
      <u-form-item
        prop="idCardNo"
        :border-bottom="true"
        :custom-style="{ backgroundColor: '#ffffff' }"
      >
        <view class="w-100 px-base bg-white u-flex-y-center">
          <view>身份证号：</view>
          <u-input
            v-model="formData.idCardNo"
            placeholder="请输入身份证号码"
            border="none"
            input-align="right"
            class="u-flex-grow"
            @focus="$refs.formRef.clearValidate('idCardNo')"
          ></u-input>
        </view>
      </u-form-item>

      <u-form-item>
        <view class="px-base pt-sm">
          <u--text type="info" text="联系方式"></u--text>
        </view>
      </u-form-item>
      <u-form-item
        prop="mobileNo"
        :border-bottom="true"
        :custom-style="{ backgroundColor: '#ffffff' }"
      >
        <view class="w-100 px-base bg-white u-flex-y-center">
          <view>手机号码：</view>
          <u-input
            v-model="formData.mobileNo"
            placeholder="请输入手机号码"
            border="none"
            input-align="right"
            class="u-flex-grow"
            @focus="$refs.formRef.clearValidate('mobileNo')"
          >
            <template slot="suffix"
              ><u-code ref="codeRef" @change="handleCodeChange"></u-code
              ><u-button type="success" size="mini" @tap="handleSendCode">{{
                codeTips
              }}</u-button></template
            >
          </u-input>
        </view>
        <u-modal
          :show="mobileCodeModalVisible"
          :async-close="true"
          title="验证码"
          confirm-text="复制验证码"
          @confirm="handleMobileCodeModalConfirm"
        >
          <view class="text-center">
            <text :style="{ fontSize: '24px' }">{{
              mobileCodeModalValue
            }}</text>
          </view>
        </u-modal>
      </u-form-item>
      <u-form-item
        prop="mobileCode"
        :border-bottom="true"
        :custom-style="{ backgroundColor: '#ffffff' }"
      >
        <view class="w-100 px-base bg-white u-flex-y-center">
          <view>验&ensp;证&ensp;码：</view>
          <u-input
            v-model="formData.mobileCode"
            placeholder="请输入手机验证码"
            border="none"
            input-align="right"
            class="u-flex-grow"
            @focus="$refs.formRef.clearValidate('mobileCode')"
          ></u-input>
        </view>
      </u-form-item>

      <u-form-item>
        <view class="px-base pt-sm">
          <u--text type="info" text="支付信息"></u--text>
        </view>
      </u-form-item>
      <u-form-item
        prop="bankCardNo"
        :border-bottom="true"
        :custom-style="{ backgroundColor: '#ffffff' }"
      >
        <view class="w-100 px-base bg-white u-flex-y-center">
          <view>银行卡号：</view>
          <u-input
            v-model="formData.bankCardNo"
            placeholder="请输入银行卡号"
            border="none"
            input-align="right"
            class="u-flex-grow"
            @focus="$refs.formRef.clearValidate('bankCardNo')"
          ></u-input>
        </view>
      </u-form-item>

      <u-form-item><!-- 当间距用 --></u-form-item>

      <view class="px-base mb-lg u-flex-y-center">
        <u-checkbox-group v-model="checkboxValues">
          <u-checkbox name="agreeTerms" label="同意"></u-checkbox>
        </u-checkbox-group>
        <text class="text-primary" :style="{ fontSize: '15px' }"
          >《服务条款》、《隐私权政策》</text
        >
      </view>

      <u-form-item>
        <u-button type="primary" @tap="handleRegister">注册</u-button>
      </u-form-item>
    </u-form>

    <u-modal
      :show="errorModalVisible"
      title="温馨提示"
      :content="errorModalValue"
      @confirm="errorModalVisible = false"
    ></u-modal>
  </view>
</template>

<script>
import {
  validateRequired,
  validateAccount,
  validatePassword,
  validatePasswordConfirm,
} from "@/utils/form-validators";
import apiAuth from "@/api/auth.js";
import apiOther from "@/api/other.js";

export default {
  data() {
    return {
      formData: {
        account: "",
        password: "",
        passwordConfirm: "",
        name: "",
        idCardNo: "",
        mobileNo: "",
        mobileCode: "",
        bankCardNo: "",
      },
      formRules: {
        // 注册时使用 trigger 是为了保证数据正确
        account: { validator: validateAccount, trigger: "blur" },
        password: { validator: validatePassword, trigger: "blur" },
        passwordConfirm: {
          validator: (rule, value, callback) =>
            validatePasswordConfirm(
              rule,
              value,
              callback,
              this.formData.password
            ),
          trigger: "blur",
        },
        name: {
          validator: (rule, value, callback) =>
            validateRequired(rule, value, callback, {
              label: "姓名",
              trim: true,
            }),
          trigger: "blur",
        },
        idCardNo: {
          validator: (rule, value, callback) =>
            validateRequired(rule, value, callback, {
              label: "身份证号",
              trim: true,
            }),
          trigger: "blur",
        },
        mobileNo: {
          validator: (rule, value, callback) =>
            validateRequired(rule, value, callback, {
              label: "手机号码",
              trim: true,
            }),
          trigger: "blur",
        },
        mobileCode: {
          validator: (rule, value, callback) =>
            validateRequired(rule, value, callback, {
              label: "验证码",
              trim: true,
            }),
          trigger: "blur",
        },
        bankCardNo: {
          validator: (rule, value, callback) =>
            validateRequired(rule, value, callback, {
              label: "银行卡号",
              trim: true,
            }),
          trigger: "blur",
        },
      },
      codeTips: "",
      mobileCodeModalVisible: false,
      mobileCodeModalValue: "",
      checkboxValues: [],
      errorModalVisible: false,
      errorModalValue: "",
    };
  },
  methods: {
    handleRegister() {
      this.$refs.formRef
        .validate()
        .then(() => {
          if (!this.checkboxValues.includes("agreeTerms")) {
            this.openErrorModal("同意《服务条款》才能注册");
            return;
          }

          uni.showLoading({ title: "正在注册", mask: true });

          apiAuth
            .add(this.formData)
            .then(() => {
              uni.hideLoading();

              const wait = 1000;
              uni.showToast({
                title: "注册成功，请使用新账号登录",
                mask: true,
                duration: wait,
              });
              setTimeout(() => {
                uni.redirectTo({ url: "/pages/LoginView/LoginView" });
              }, wait);
            })
            .catch(() => uni.hideLoading());
        })
        .catch((errors) => {
          this.openErrorModal(errors[0].message);
        });
    },
    handleSendCode() {
      if (this.$refs.codeRef.canGetCode) {
        this.$refs.formRef.validateField("mobileNo", (errors) => {
          if (!errors.length) {
            uni.showLoading({ title: "正在发送验证码", mask: true });

            apiOther
              .sendMobileCode({
                mobileNo: this.formData.mobileNo,
              })
              .then((res) => {
                uni.hideLoading();
                uni.$u.toast("验证码发送成功");
                this.$refs.codeRef.start();

                // 没有实际的短信服务，通过接口返回 code，延迟后弹出
                this.mobileCodeModalValue = "";
                setTimeout(() => {
                  uni.hideToast();
                  this.mobileCodeModalValue = res.data.code;
                  this.mobileCodeModalVisible = true;
                }, 1000);
              })
              .catch(() => uni.hideLoading());
          }
        });
      }
    },
    handleCodeChange(text) {
      this.codeTips = text;
    },
    handleMobileCodeModalConfirm() {
      uni.setClipboardData({
        data: String(this.mobileCodeModalValue),
        success: () => {
          this.mobileCodeModalVisible = false;
        },
        fail: (e) => {
          uni.showToast({
            icon: "error",
            title: "复制失败",
          });
        },
      });
    },
    openErrorModal(content) {
      this.errorModalValue = content;
      this.errorModalVisible = true;
    },
  },
};
</script>

<style></style>
